<template>
  <el-dialog :title="'写入源'" :visible.sync="dialogJSFormVisible" :append-to-body="true" :close-on-click-modal="false" :before-close="handleBeforeClose">
    <el-form label-position="right" label-width="150px" :model="writerForm" :rules="rules">
      <el-form-item label="数据存储：" prop="sourceId" label-width="150px">
        <el-select v-model="writerForm.sourceId" filterable @change="rDsChange">
          <el-option v-for="item in rDsList" :key="item.id" :label="item.sourceName" :value="item.id" />
        </el-select>
      </el-form-item>
      <!-- <el-form-item label="数据存储：">
        <el-select v-model="writerForm.increment" filterable @change="changeType">
          <el-option v-for="item in dictList('data_get_is_increment')" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="数据更新方式：">
        <el-select v-model="writerForm.incrementUpdateStyle" filterable @change="handleSelectChange">
          <el-option v-for="item in dictList('data_update_method_new')" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <!--      合并配置-->
      <el-form-item label="配置映射：">
        <el-col style="border: 1px dashed #bbb">
          <el-table :data="selColumnList" style="width: 100%" :header-cell-style="{ 'text-align': 'center' }" :cell-style="{ 'text-align': 'center' }">
            <!-- 表格列配置 -->
            <el-table-column label="id" prop="id" :editable="true" v-if="false">
              <template slot-scope="scope">
                <!-- 使用 el-input 进行编辑 -->
                <el-input v-model="scope.row.id" @blur="handleEdit(scope.row, 'name')"></el-input>
              </template>
            </el-table-column>
            <el-table-column prop="tableName" label="源数据" width="180" align="center"> </el-table-column>

            <el-table-column label="目标模型" prop="tableComment" align="center">
              <template slot-scope="scope">
                <!-- <el-select v-model="scope.row.sourceTable" placeholder="请选择唯一字段" @change="selectSourceTable(scope.row.sourceTable,scope.$index)"> -->
                <el-select v-model="scope.row.sourceTable" placeholder="请选择目标模型" @change="selectSourceTable(scope.row.sourceTable, scope.$index)">
                  <el-option v-for="item in wTbList" :key="item.id" :label="item.tableName" :value="item.tableName" :disabled="item.disabled"> </el-option>
                </el-select>
              </template>
            </el-table-column>
            <!-- <el-table-column label="字段映射" prop="tableComment" :editable="true" align="center">
              <template slot-scope="scope">
                &lt;!&ndash; 使用 el-input 进行编辑 &ndash;&gt;
                <el-input v-model="scope.row.tableComment"></el-input>
              </template>
            </el-table-column> -->
            <el-table-column label="操作" min-width="180" class-name="small-padding fixed-width" fixed="right" align="center">
              <template slot-scope="scope">
                <el-button size="small" type="text" @click="openSetRelation(scope.row, scope.$index)">设置</el-button>
              </template>
            </el-table-column>
            <!-- 其他列配置 -->
          </el-table>
        </el-col>
      </el-form-item>
      <el-dialog title="映射关系设置" :visible.sync="dialogTableVisibleRelation" :append-to-body="true" :close-on-click-modal="false">
        <el-descriptions title="">
          <el-descriptions-item label="目标文件" :span="24">{{ showTable }}</el-descriptions-item>
          <el-descriptions-item label="源文件" :span="24">{{ showResourceTable }}</el-descriptions-item>
        </el-descriptions>
        <el-table
          :data="nowcolumnList"
          :header-cell-style="{ 'text-align': 'center' }"
          :cell-style="{ 'text-align': 'center' }"
          style="border: 1px dashed #bbb; overflow: auto"
          height="400px"
          fixed-header
        >
          <el-table-column property="columnName" label="字段名称" width="150"></el-table-column>
          <el-table-column property="dataType" label="字段类型" width="200"></el-table-column>
          <el-table-column label="源字段名称">
            <template slot-scope="scope">
              <el-select v-model="scope.row.sourceColumn" placeholder="选择对应源字段" @change="selectResourceColumn(scope.row)">
                <el-option v-for="item in wColumnList" :key="item.id" :label="item.columnName" :value="item.columnName" :disabled="item.disabled"> </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column label="唯一字段">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.status" @change="handleSwitchChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
        </el-table>
        <div class="dialog-button-container" style="text-align: center; margin-top: 20px">
          <el-button @click="dialogTableVisibleRelation = false">取消</el-button>
          <el-button type="primary" @click="sureSetRelation">确认</el-button>
        </div>
      </el-dialog>
    </el-form>
       <!-- <el-button  type="primary" style="margin-top: 12px;margin-bottom: 12px;"   @click="createJSJob">提交</el-button> -->
    <el-row type="flex" justify="center" align="right">
      <el-button type="primary" style="width: 15%; margin-top: 5%" @click="createJSJob">提交</el-button>
    </el-row>
  </el-dialog>
</template>

<script>
import { listDataSource } from '@/api/metadata/sqlconsole'
import { getTableList } from '@/api/masterdata/masterdataTable'
import { fetchcolumnList } from '@/api/metadata/column'
import Bus from '../busWriter'
export default {
  name: 'TableWriter',
  // props: ['writerInfo','readerInfo'],
  props: {
    writerInfo: {},
    readerInfo: {},
  },
  data() {
    return {
      nowcolumnList: [],
      showTable: [],
      showResourceTable: [],
      nowColumnSelectIndex: 0,
      dialogTableVisibleRelation: false,
      dateRange: [],
      dialogJSFormVisible: true,
      dialogFormVisible: false,
      dialogFormVisibleForYou: false,
      jdbcDsQuery: {
        current: 1,
        size: 200,
        ascs: 'datasource_name',
      },
      wDsList: [],
      schemaList: [],
      rDsList: [],
      wColumnList: [],
      columns: [],
      fromTableName: '',
      wTbList: [],
      dataSource: '',
      createTableName: '',
      writerForm: {
        increment: '1',
        incrementUpdateStyle: 'insert',
        selColumnList: [],
      },
      // readerForm: this.getReaderData(),
      rules: {
        targetDatasourceId: [{ required: true, message: '数据库源为必填项', trigger: 'change' }],
        tableName: [{ required: true, message: 'this is required', trigger: 'change' }],
      },
      key: '',
      selColumnList: [],
      nowIndex: 0,
    }
  },
  created() {
    // console.log("得到的回传信息"+JSON.stringify(this.readerInfo))
    // console.log("得到的回传信息====1"+JSON.stringify(this.readerInfo))
    // console.log("得到的回传信息===="+JSON.stringify(this.readerInfo.tableId))
    this.selColumnList = this.readerInfo.tableId
    this.writerForm = this.writerInfo
    // if(!this.writerInfo.increment){
    //   this.writerForm.increment = '1'
    // }
    // if(!this.writerInfo.incrementUpdateStyle){
    //   this.writerForm.incrementUpdateStyle = 'insert'
    // }
    this.getJdbcDs()
  },
  methods: {
    sureSetRelation() {
      this.selColumnList[this.nowColumnSelectIndex].columnList = this.nowcolumnList
      // console.log("====="+JSON.stringify(this.selColumnList))
      this.dialogTableVisibleRelation = false
    },
    selectSourceTable(value, index) {
      console.log('---------' + JSON.stringify(this.wTbList))
      const selectedOption = this.wTbList.find((option) => option.tableName === value)
      const id = selectedOption.id
      this.selColumnList[index].sourceTableId = id
      const name = selectedOption.tableName
      console.log('选中的id:', id)
      console.log('选中的名称:', name)
      this.rTbChange(id)
      console.log('选中的名称:', JSON.stringify(this.wColumnList))
      // this.selColumnList[this.nowColumnSelectIndex].columnList = this.wColumnList
      // console.log("2---------"+JSON.stringify(this.selColumnList))
    },
    openSetRelation(scope, index) {
      getTableList({ sourceId: this.writerForm.sourceId }).then((res) => {
        if (res.data.code === 200) {
          this.wTbList = res.data.data
        }
      })
      const table = this.wTbList.find((option) => option.tableName === scope.sourceTable)
      this.rTbChange(table.id)
      this.showTable = this.selColumnList[index].table
      this.showResourceTable = scope.sourceTable
      // console.log("1---------"+JSON.stringify(this.selColumnList))
      // console.log("scope ="+JSON.stringify(scope))
      // console.log("scope =="+JSON.stringify(scope.columnList))
      // console.log("当前点击序号="+index)
      this.nowColumnSelectIndex = index
      this.nowcolumnList = scope.columnList
      this.dialogTableVisibleRelation = true
    },
    rDsChange(e) {
      this.wTbList = []
      this.writerForm.sourceName = ''
      this.writerForm.sourceId = e
      this.rDsList.find((item) => {
        if (item.id === e) {
          this.writerForm.sourceName = item.sourceName
        }
      })
      Bus.sourceId = e
      this.$emit('selectDataSource', this.dataSource)
      // 获取可用表

      this.getTables('reader')
    },
    addTj(row, index) {
      var onlyColumn = row.onlyColumn
      var dateRange = row.margeDateRange
      this.selColumnList[this.nowIndex].margeOnlyColumn = onlyColumn
      this.selColumnList[this.nowIndex].sourceTable = onlyColumn
      this.selColumnList[this.nowIndex].margeDateRange = dateRange
      this.selColumnList[this.nowIndex].writeStime = dateRange[0]
      this.selColumnList[this.nowIndex].writeEtime = dateRange[1]
      // console.log('选中的值唯一:========'+onlyColumn);
      // console.log('选中的值时间:========'+JSON.stringify(this.selColumnList));
      // alert(index);
      this.dialogFormVisible = false
    },
    addTjSql(row, index) {
      var sql = row.writerSql

      this.selColumnList[this.nowIndex].writerSql = sql
      // console.log('选中的值时间:========'+JSON.stringify(this.selColumnList));
      // alert(index);
      this.dialogFormVisibleForYou = false
    },
    handleRadioChange(value) {
      // 当选项变化时触发
      console.log('选中的值:', value)
      this.selColumnList[this.nowIndex].replaceStyle = value
      if (value == 1) {
        this.dialogFormVisible = true
      }
      if (value == 2) {
        this.dialogFormVisibleForYou = true
      }
    },
    changeValueforList(row, val, index) {
      // alert(index)
      this.selColumnList[index].replaceStyle = val
      row.replaceStyle = val
    },
    handleReplaceStyleChange(value) {
      console.log('选项发生变化，新的值为：', value)
    },
    handleDateRangeChange() {
      // 处理日期范围选择器的值变化事件
      if (Array.isArray(this.dateRange) && this.dateRange.length === 2) {
        this.readerForm.effectTime = this.dateRange[0]
        this.readerForm.failureTime = this.dateRange[1]
        console.log('开始日期:', this.startDate)
        console.log('结束日期:', this.endDate)
      } else {
        this.startDate = ''
        this.endDate = ''
      }
    },
    handleBeforeClose(done) {
      this.createJSJob()
    },
    createJSJob() {
      this.dialogJSFormVisible = false
      this.writerForm.selColumnList = this.selColumnList
      this.$emit('change', this.writerForm)
    },
    //获取列名
    rTbChange(id) {
      this.wTbList.forEach((item) => {
        if (item.id == id) {
          this.writerForm.tableName = item.tableName
        }
      })
      fetchcolumnList({ sourceId: id }).then((res) => {
        if (res.data.code === 0) {
          this.wColumnList = res.data.data
        } else {
          this.$message.error(res.data.msg)
        }
      })
    },
    rest() {
      this.wColumnList = []
      this.wTbList = []
      this.writerForm = {
        sourceId: undefined,
        tableId: '',
        tableName: '',
        checkAll: false,
        isIndeterminate: true,
        tableSchema: '',
        status: 'false',
        sourceName: undefined,
        preSql: '', //前置sql语句
        postSql: '',
        columns: [],
      }
    },
    handleSelectChange(value) {
      // 处理 el-select 的选项变化事件
      console.log('选中的选项:', value)
      // this.selColumnList[this.nowIndex].margeOnlyColumn = value
      // this.writerForm.incrementUpdateStyle = value
      // 在这里可以执行其他操作
    },
    selectResourceColumn(value) {
      // 处理 el-select 的选项变化事件
      console.log('选中的选项:' + JSON.stringify(this.nowcolumnList))

      // this.selColumnList[this.nowIndex].margeOnlyColumn = value
      // this.writerForm.incrementUpdateStyle = value
      // 在这里可以执行其他操作
    },
    //选择是否创建表
    changeType(e) {
      this.key = e
      console.log(this.readerInfo, 'readerInfo===========')
      if (e == 'true') {
        this.wColumnList = this.readerInfo.columns
        this.writerForm.tableId = this.readerInfo.tableId
        this.writerForm.tableName = this.readerInfo.tableName
      } else {
        getTableList({ sourceId: this.writerForm.targetDatasourceId }).then((res) => {
          if (res.data.code === 200) {
            this.wTbList = res.data.data
          }
        })
        this.wColumnList = []
        // 获取可用表
        if (this.writerForm.tableId) {
          fetchcolumnList({ sourceId: this.writerForm.tableId }).then((res) => {
            if (res.data.code === 0) {
              this.wColumnList = res.data.data
            } else {
              this.$message.error(res.data.msg)
            }
          })
        }
      }
    },
    // 获取可用数据源
    getJdbcDs() {
      this.loading = true
      listDataSource().then((response) => {
        this.rDsList = response.data.data
        this.loading = false
      })
    },
    // 获取表名
    getTables(type) {
      getTableList({ sourceId: this.writerForm.sourceId }).then((res) => {
        if (res.data.code === 200) {
          // alert("123")
          this.wTbList = res.data.data
        }
      })
    },
    wDsChange(e) {
      // 清空
      this.writerForm.tables = []

      this.wDsList.find((item) => {
        if (item.id === e) {
          this.writerForm.sourceName = item.sourceName
          this.dataSource = item
        }
      })
      this.changeType(this.key)
      Bus.sourceId = e
      // this.$emit('selectDataSource', this.dataSource)
    },
    wHandleCheckAllChange(val) {
      this.writerForm.columns = val ? this.wColumnList : []
      this.writerForm.isIndeterminate = false
    },
    wHandleCheckedChange(value) {
      const checkedCount = value.length
      this.writerForm.checkAll = checkedCount === this.wColumnList.length
      this.writerForm.isIndeterminate = checkedCount > 0 && checkedCount < this.wColumnList.length
    },
    getData() {
      if (Bus.sourceId) {
        this.writerForm.sourceId = Bus.SourceId
      }
      return this.writerForm
    },
    getReaderData() {
      return this.$parent.getReaderData()
    },
    getTableName() {
      return this.fromTableName
    },
    handleRowClick(row) {
      // 在 @row-click 事件中获取行号
      this.nowIndex = this.selColumnList.indexOf(row)
      console.log('点击的行号：', this.nowIndex)
    },
  },
}
</script>
<style lang="scss" scoped>
::v-deep(::-webkit-scrollbar) {
  display: block !important;
}
</style>
